const express = require('express');
const work = express.Router() //创建路由

const { User } = require("../../mod/user")
const { Work } = require("../../mod/work")
const { Middle } = require("../../mod/middle")
const { Comment } = require("../../mod/comment");
const { Tool } = require("../../mod/tool");

const { Jurisdiction } = require("../../mod/jurisdiction")

const multer = require("multer")

const fs=require("fs")

// 提供院校结构
work.get("/structure", async (req, res) => {
    let data = await Tool.find()
    res.json({
        code: 200,
        msg: "获取院校结构成功",
        data
    })
})

// 毕业生就业信息上传
work.post("/uploadInfo", async (req, res) => {
    // work_username
    // console.log(req.body)
    let { work_sex, work_username, work_xueyuan, work_zhuanye, work_fangshi, work_xuezhi, work_xueli, work_shengyuan, work_kun_grade, work_jiuye, work_danwei, work_dizhi } = req.body
    if (work_username.trim() == "") {
        req.body.work_username = "匿名用户"
    }

    if (work_danwei.trim() == "") {
        req.body.work_danwei = "升学"
    }

    // if (work_dizhi.length == 0) {
    //     console.log("[]")
    //     req.body.work_danwei = ["升学"]
    // }

    try {
        let data = await new Work(req.body).save()
        if (data) {
            res.json({
                code: 200,
                msg: "毕业生就业信息上传成功",
            })
        }
    } catch (err) {
        console.log(err)
        res.json({
            code: 201,
            msg: "毕业生就业信息上传失败，请重试",
            data: err
        })
    }

})


// 用户修改基本信息
// 新建一个仓库
var storage = multer.diskStorage({
    //设置上传后的文件路径
    destination: function (req, file, cb) {
        cb(null, './public/uploads/')
    },
    //给上传文件重命名，以防命名重复
    filename: function (req, file, cb) {
        cb(null, `${Date.now()} + ${file.originalname}`)
    }
})

// 配置一个接收器，用于使用仓库
var upload = multer({
    storage: storage
})
// 单名称单文件上传   single     
// 单名城多文件    array
// 多名称多文件       fields   upload.fields([{name:'logo'},{name:'headerimg'}])     



// 专门用于处理 前端传过来的 base64格式图片
function base64Company(imgData,basename){
    return new Promise((resive,reject)=>{
    //过滤data:URL
    let base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
    let dataBuffer = Buffer.from(base64Data, 'base64');
    // 处理名字
    let filename= `./public/uploads/${Date.now()} + ${basename}.png`
    fs.writeFile(filename, dataBuffer, function (err) {
        if (err) {
            reject(err)
        } else {
          resive("ok")
        }
    });
    })
}


// 这个是测试接口
work.post('/ceshi', async (req, res) => {
    // console.log(req.body)
    //接收前台POST过来的base64
    let { company_3_3, company_id_3_2, certificates_3_3, userheader_register3_3 } = req.body
    base64Company(certificates_3_3,'certificates_3_3')
    res.json({
        data: req.body
    })
})

// ---老师提交审核信息
work.post("/putInfoTeacher", upload.single("headerurl"), async (req, res) => {
    // console.log(req.body)
    let { _id, username } = req.body

    // 老师提交信息需要审核
    let url = req.file.filename   //单文件上传  req.file  ;  多文件上传  req.files
    // 直接更新名字
    let data4 = await User.updateOne({ _id }, { username })
    let data5 = await User.findOne({ _id })
    // 先查看他是否已经通过了教师验证
    let data = await User.findOne({ _id })
    if (data.shengfen != 0) {  // 表示他不是学生,不再需要中间验证，可以直接修改身份及相关个人信息
        let data1 = await User.updateOne({ _id }, { username })
        if (data1.n == 1) {
            let data2 = await User.findOne({ _id })
            return res.json({
                code: 200,
                msg: "跟新信息成功",
                data: data2
            })
        }
    } else {
        // 这是需要验证的老师
        // 先保存到中间验证表中，等待admin来验证，通过后才能认证他的教师身份
        // 需要先查看这位老师是否有还没审核的信息，先清除
        let data2 = await Middle.findOne({ middle_id: _id })
        if (data2 != null) {
            // 先要清除原来提交的审核信息
            let data3 = await Middle.deleteOne({ middle_id: _id })
            if (data3.n != 1) {
                return res.json({
                    code: 201,
                    msg: "提交失败，请重新提交"
                })
            }
        }
        let data1 = await new Middle({
            middle_id: _id,
            img_url: `uploads/${url}`
        }).save()
        if (data1 !== null) {
            return res.json({
                code: 200,
                msg: "提交成功，等待管理员审核",
                data: data5
            })
        }
        res.json({
            code: 201,
            msg: "提交失败，请重新提交"
        })


    }


})

// ----学生修改个人信息
work.post("/putInfoStudent", async (req, res) => {
    // 用户id useranme
    let { _id } = req.body
    let data = await User.updateOne({ _id }, req.body)
    if (data.n == 1) {
        // 修改用户信息成功
        // 返回最新的信息
        let data1 = await User.findOne({ _id })
        if (data1 == null) {
            return res.json({
                code: 201,
                msg: "跟新用户信息成功，请重新登陆"
            })
        }
        res.json({
            code: 200,
            msg: "跟新用户信息成功",
            data: data1
        })


    } else {
        res.json({
            code: 202,
            msg: "修改用户信息失败"
        })
    }

})

// 获取所有老师提交的审核信息
work.get("/getallmiddleinfo", async (req, res) => {
    let { _id } = req.query
    let data = await User.findOne({ _id })
    if (data.shengfen == 2) {
        let data1 = await Middle.find().populate("middle_id").exec()
        res.json({
            code: 200,
            msg: "获取成功",
            data: data1
        })
    } else {
        res.json({
            code: 203,
            msg: "获取信息失败"
        })
    }
})

// 通过了审核
work.post("/pass", async (req, res) => {
    // admin_id 审核的admin用户的id  
    // middle_id 需要被审核的项_id
    // user_id 需要被审核的学生的_id
    let { admin_id, middle_id, user_id } = req.body
    // 先查看该用户是不是管理员
    let userdata = await User.findOne({ _id: admin_id, shengfen: 2 })
    if (userdata == null) {
        // 不是管理员
        return res.json({
            code: 404,
            msg: "你不是管理员，没有权限"
        })
    }
    else {
        // 重新赋予用户老师的权限
        // 获取老师的权限路由
        let teacherData = await Jurisdiction.findOne({ user_grade: 1 })
        let user_jurisdiction_routerlist = teacherData.jurisdiction_routerlist
        // 将用户修改为老师
        let data = await User.updateOne({ _id: user_id }, { shengfen: 1, user_jurisdiction_routerlist })
        if (data.n != 1) {
            return res.json({
                code: 201,
                msg: "审核没通过"
            })
        }
        // 删除对应的审核信息
        let data1 = await Middle.deleteOne({ _id: middle_id })

        if (data.n != 1) {
            return res.json({
                code: 201,
                msg: "审核通过，但记录删除失败,请重试"
            })
        }

        return res.json({
            code: 200,
            msg: "审核通过"
        })
    }



})

// 没通过审核
work.post("/nopass", async (req, res) => {
    // user_id
    // 删除对应的审核信息
    let { middle_id } = req.body
    let data1 = await Middle.deleteOne({ _id: middle_id })
    if (data1.n == 1) {
        return res.json({
            code: 200,
            msg: "删除记录成功"
        })
    } else {
        return res.json({
            code: 201,
            msg: "审核没通过，没删除记录"
        })
    }

})

// 模糊查询
work.get("/getallStudentForm", async (req, res) => {
    // 开启模糊查询   work_username  
    let { work_username } = req.query
    work_username = new RegExp(work_username, "i")     //i 忽略大小写
    let data = await Work.find({
        $or: [

            {
                work_username: { $regex: work_username }
            }
        ]
    })

    res.json({
        code: 200,
        msg: "获取成功",
        count: data.length,
        data
    })
})

// 条件搜索
work.get("/filterStudentForms", async (req, res) => {
    // num(第几页)    pageSize (每页多少条)
    let { num = 1,
        pageSize = 8,
    } = req.query

    skip = (pageSize - 0) * (num - 0 - 1)    //跳过多少条，

    let obj = {}
    for (var index in req.query) {
        if (!index || req.query[index] == '' || index == 'num' || index == 'pageSize') {
            continue
        }
        obj[index] = req.query[index]

    }

    let data = await Work.find(obj).skip(skip).limit(pageSize - 0)
    let count = await Work.find(obj).countDocuments()

    res.json({
        code: 200,
        msg: "获取成功",
        count,
        data
    })
})


// echarts图表1  第一个图表，主要展示 就业率
work.get("/echarts", async (req, res) => {
    // let time1 = Date.now()
    // 返回近五年的数据
    // 全部的就业数据分布
    let obj = {}
    for (var index in req.query) {
        if (!index || req.query[index] == '') {
            continue
        }
        obj[index] = req.query[index]
    }
    // console.log(obj)

    let data = await Work.find(obj, { work_biye_time: 1, work_jiuye: 1, work_xueli: 1, _id: 0 })

    // 对数据进行处理
    let biye_timearr = ["2016", "2017", "2018", "2019", "2020"]
    let series = [
        {
            name: "就业",
            type: "line",
            // stack: "总人数",
            data: [0, 0, 0, 0, 0],
        },
        {
            name: "灵活就业",
            type: "line",
            // stack: "总人数",
            data: [0, 0, 0, 0, 0],
        },
        {
            name: "待就业",
            type: "line",
            // stack: "总人数",
            data: [0, 0, 0, 0, 0],
        },
        {
            name: "升学",
            type: "line",
            // stack: "总人数",
            data: [0, 0, 0, 0, 0],
        },
    ]

    // let time3 = Date.now()
    data = JSON.parse(JSON.stringify(data))
    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < biye_timearr.length; j++) {
            if (data[i].work_biye_time == biye_timearr[j]) {
                for (let a = 0; a < series.length; a++) {
                    if (data[i].work_jiuye == series[a].name) {
                        series[a].data[j] = series[a].data[j] + 1
                        break
                    }
                }
                break
            }
        }
    }



    // let time2 = Date.now()
    // console.log(`查数据库消耗了 ---- ${(time3 - time1) / 1000}s`)
    // console.log(`处理数据消耗了 ---- ${(time2 - time3) / 1000}s`)
    // console.log(`一共消耗了 ---- ${(time2 - time1) / 1000}s`)
    res.json({
        code: 200,
        msg: "获取数据成功",
        data: series
    })
})

// echarts图表2  第2个图表，主要展示 学历结构百分比
work.get("/echartsstructure", async (req, res) => {
    // 直接查询5年全部的本科，研究生，博士数量 本年的全部毕业生 计算百分比
    let biye_timearr = ["2016", "2017", "2018", "2019", "2020"]
    let series = [
        {
            name: "本科",
            type: "line",
            data: [0, 0, 0, 0, 0],    // 百分比
        },
        {
            name: "研究生",
            type: "line",
            data: [0, 0, 0, 0, 0],
        },
        {
            name: "博士",
            type: "line",
            data: [0, 0, 0, 0, 0],
        }
    ]

    let data = await Work.find({}, { work_biye_time: 1, work_xueli: 1, _id: 0 })
    data = JSON.parse(JSON.stringify(data))
    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < biye_timearr.length; j++) {
            if (data[i].work_biye_time == biye_timearr[j]) {
                for (let a = 0; a < series.length; a++) {
                    if (data[i].work_xueli == series[a].name) {
                        series[a].data[j] = series[a].data[j] + 1
                        break
                    }
                }
                break
            }
        }
    }

    res.json({
        code: 200,
        msg: "获取成功",
        data: series
    })
})

// echarts 图表3，主要显示就业的同学的分布 map
work.get("/echartsmap", async (req, res) => {

    let data = await Work.find(req.query, { work_dizhi: 1, _id: 0 })

    let arr = [
        { name: '北京市', value: 0 },
        { name: '天津市', value: 0 },
        { name: '河北省', value: 0 },
        { name: '山西省', value: 0 },
        { name: '内蒙古自治区', value: 0 },
        { name: '辽宁省', value: 0 },
        { name: '吉林省', value: 0 },
        { name: '黑龙江省', value: 0 },
        { name: '上海市', value: 0 },
        { name: '江苏省', value: 0 },
        { name: '浙江省', value: 0 },
        { name: '安徽省', value: 0 },
        { name: '福建省', value: 0 },
        { name: '江西省', value: 0 },
        { name: '山东省', value: 0 },
        { name: '河南省', value: 0 },
        { name: '湖北省', value: 0 },
        { name: '湖南省', value: 0 },
        { name: '广东省', value: 0 },
        { name: '广西壮族自治区', value: 0 },
        { name: '海南省', value: 0 },
        { name: '重庆市', value: 0 },
        { name: '四川省', value: 0 },
        { name: '贵州省', value: 0 },
        { name: '云南省', value: 0 },
        { name: '西藏自治区', value: 0 },
        { name: '陕西省', value: 0 },
        { name: '甘肃省', value: 0 },
        { name: '青海省', value: 0 },
        { name: '宁夏回族自治区', value: 0 },
        { name: '新疆维吾尔自治区', value: 0 },
        { name: '台湾省', value: 0 },
        { name: '香港特别行政区', value: 0 },
        { name: '澳门特别行政区', value: 0 }
    ]

    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < arr.length; j++) {
            if (data[i].work_dizhi[0] == arr[j].name) {
                arr[j].value += 1
                break
            }
        }
    }

    res.json({
        code: 200,
        msg: "获取成功",
        data: arr

    })
})


// 第三个echarts图表，展示近五年的各个学历下的毕业男女数量
work.get("/sexstract", async (req, res) => {
    // 条件 学历  默认不设置学历
    let obj = {}
    for (var index in req.query) {
        if (!index || req.query[index] == '') {
            continue
        }
        obj[index] = req.query[index]
    }

    let data = await Work.find(obj, { work_sex: 1, work_xueli: 1, work_biye_time: 1, _id: 0 })
    let biye_timearr = ["2016", "2017", "2018", "2019", "2020"]
    let series = [
        {
            name: "男",
            type: "bar",
            data: [
                0,
                0,
                0,
                0,
                0,
            ],
        },
        {
            name: "女",
            type: "bar",
            data: [
                0,
                0,
                0,
                0,
                0,
            ],
        },
    ]
    data = JSON.parse(JSON.stringify(data))
    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < biye_timearr.length; j++) {
            if (data[i].work_biye_time == biye_timearr[j]) {
                for (let a = 0; a < series.length; a++) {
                    if (data[i].work_sex == series[a].name) {
                        series[a].data[j] = series[a].data[j] + 1
                        break
                    }
                }
                break
            }
        }
    }

    res.json({
        code: 200,
        msg: "获取成功",
        data: series
    })

})

// 评论点赞/踩
// 点赞，踩，不选 三选一
work.post("/iszan", async (req, res) => {
    // comment_id(被评论的评论_id) user_id(点赞人的id)  
    // isZan (0 中立,1赞 ,2踩)
    let { comment_id, user_id, isZan } = req.body
    // console.log(req.body)
    let data = await Comment.findOne({ _id: comment_id })  // 获取该评论的点赞arr
    // console.log(data)
    let arr = data.up_number
    let arr1 = data.lower_number
    if (isZan == 1) {  // 赞
        // 先查看是否点过 踩，并清除
        let index1 = arr1.indexOf(user_id)
        if (index1 != -1) {  // 表示原来是踩 ，先清空踩
            arr1.splice(index1, 1)
            let data1 = await Comment.updateOne({ _id: comment_id }, { lower_number: arr1 })
            if (data1.n != 1) {
                return res.json({
                    code: 202,
                    msg: "点赞失败，依然保持踩"
                })
            }
        }

        // 再更新点赞
        arr.push(user_id)
        let data1 = await Comment.updateOne({ _id: comment_id }, { up_number: arr })
        if (data1.n == 1) {
            res.json({
                code: 200,
                msg: "点赞成功"
            })
        } else {
            res.json({
                code: 201,
                msg: "点赞失败"
            })
        }
    } else if (isZan == 2) {  // 踩
        // 先查看是否点过赞，并清除
        let index3 = arr.indexOf(user_id)
        if (index3 != -1) {  // 表示原来是点赞，先清除点赞
            arr.splice(index3, 1)
            let data1 = await Comment.updateOne({ _id: comment_id }, { up_number: arr })
            if (data1.n != 1) {
                return res.json({
                    code: 202,
                    msg: "踩失败，依然保持点赞"
                })
            }
        }

        arr1.push(user_id)
        let data1 = await Comment.updateOne({ _id: comment_id }, { lower_number: arr1 })
        if (data1.n == 1) {
            res.json({
                code: 200,
                msg: "踩成功"
            })
        } else {
            res.json({
                code: 201,
                msg: "点赞失败"
            })
        }
    } else if (isZan == 0) { // 中立
        // 先查看原来是否存在,两个不能同时存在
        let index1 = arr.indexOf(user_id)
        let index2 = arr1.indexOf(user_id)
        if (index1 != -1 && index2 != -1) {
            // 全部清空
            arr.splice(index1, 1)
            let data1 = await Comment.updateOne({ _id: comment_id }, { up_number: arr })
            arr1.splice(index2, 1)
            let data2 = await Comment.updateOne({ _id: comment_id }, { lower_number: arr })

        }
        if (index1 == -1 && index2 == -1) {
            return res.json({
                code: 200,
                msg: "原来不存在评价，取消点赞或踩失败"
            })
        }

        if (index1 != -1 && index2 == -1) {   // 取消赞
            arr.splice(index1, 1)
            let data1 = await Comment.updateOne({ _id: comment_id }, { up_number: arr })
            // console.log("取消赞")
            if (data1.n == 1) {
                return res.json({
                    code: 200,
                    msg: "取消点赞成功"
                })
            }

            res.json({
                code: 200,
                msg: "取消点赞失败"
            })
        }

        else if (index1 == -1 && index2 != -1) {   // 取消踩
            arr1.splice(index2, 1)
            let data1 = await Comment.updateOne({ _id: comment_id }, { lower_number: arr })
            if (data1.n == 1) {
                return res.json({
                    code: 200,
                    msg: "取消踩成功"
                })
            }

            res.json({
                code: 200,
                msg: "取消踩失败"
            })
        }

    }

})

// 撤回评论
// 如果是二级评论，直接删除
// 如果是楼主，还需要把相关评论全删除

work.get("/delComment", async (req, res) => {
    // 评论id  删除评论的人的id 和发表评论人的id
    let { comment_id, user_id, isOne } = req.query
    // 先判断删除评论的人是不是admin用户 user_id
    let adminDate = await User.findOne({ _id: user_id, shengfen: 2 })

    if (adminDate != null) {        // 表示user_id用户是admin用户，可以直接删除评论及相关回复

        if (isOne) {  // 楼主评论
            // 先删除楼主评论验证身份
            let data = await Comment.deleteOne({ _id: comment_id })

            if (data.n == 1) {
                // 再删除子评论
                let data1 = await Comment.deleteMany({ zhu_id: comment_id })
                // console.log(data1)
                return res.json({
                    code: 200,
                    msg: "删除成功"
                })
            } else {
                return res.json({
                    code: 201,
                    msg: "删除失败2"
                })
            }

        } else {    // 普通二级评论
            let data = await Comment.deleteOne({ _id: comment_id })

            if (data.n == 1) {
                return res.json({
                    code: 200,
                    msg: "删除成功"
                })
            }
            return res.json({
                code: 201,
                msg: "删除失败1"
            })
        }
    }

    // 自己撤销评论
    if (isOne) {  // 楼主评论
        // 先删除楼主评论验证身份
        let data = await Comment.deleteOne({ _id: comment_id, push_user_id: user_id })

        if (data.n == 1) {
            // 再删除子评论
            let data1 = await Comment.deleteMany({ zhu_id: comment_id })
            // console.log(data1)
            res.json({
                code: 200,
                msg: "删除成功"
            })
        } else {
            res.json({
                code: 201,
                msg: "删除失败2"
            })
        }

    } else {    // 普通二级评论
        let data = await Comment.deleteOne({ _id: comment_id, push_user_id: user_id })

        if (data.n == 1) {
            return res.json({
                code: 200,
                msg: "删除成功"
            })
        }
        res.json({
            code: 201,
            msg: "删除失败1"
        })
    }

})

// 发表评论
work.post("/addComment", async (req, res) => {
    // comment_id(回复的当前的评论的id,可选，不传就是楼主) push_user_id(发表评论人的id) 
    // zhu_id(回复的当前的评论的楼主评论id,可选，不传就是楼主)
    // push_usered_id(被评论的人的id,没有就是楼主) comment_content(评论的具体内容)
    // isOne(true  楼主 || false 回复)
    // console.log(req.body)
    let { push_user_id, comment_content, isOne } = req.body
    let push_time = Date.now()
    if (isOne) {  // 楼主
        let data = await new Comment({
            push_user_id, comment_content, isOne, push_time
        }).save()

        if (data != null) {
            res.json({
                code: 200,
                msg: "发表评论成功",
                data
            })
        }
    } else {   // 回复评论
        let data = await new Comment({

            push_user_id,
            comment_content,
            isOne,
            push_time,
            comment_id: req.body.comment_id,
            push_usered_id: req.body.push_usered_id,
            zhu_id: req.body.zhu_id
        }).save()

        if (data != null) {
            res.json({
                code: 200,
                msg: "发表评论成功",
                data
            })
        }
    }
})



// 获取前5条的楼主评论及回复
work.get("/allcomments", async (req, res) => {
    // book_id  
    // ishot( 按时间 false | 热度排序 true ) 默认按时间排序
    let { ishot, num = 1 } = req.query

    pageSize = 5   //m每页多少条
    // skip = pageSize * (num - 1)    //跳过多少条，

    if (ishot == 'true') {  // 获取按热度排序的评论
        let data = await Comment.find({ isOne: true }).populate("push_user_id")

        let count = await Comment.find({}).countDocuments()

        let dataarr1 = JSON.parse(JSON.stringify(data))
        // 上面获取到的都是一级评论
        // 遍历一级评论，获取各个评论下的回复评论，按时间降序排列
        for (let i = 0; i < dataarr1.length; i++) {
            let data1 = await Comment.find({ zhu_id: data[i]._id }).populate("push_user_id").populate("push_usered_id").sort({ push_time: -1 })
            dataarr1[i].er_arr = data1 || []
        }

        // 对获取的数据进行热度排序 按照回复数降序
        dataarr1.sort(function (a, b) {
            return b.er_arr.length - a.er_arr.length
        })

        let dataarr2 = []
        let length = 0

        if (num * pageSize < dataarr1.length) {
            length = num * pageSize
        } else {
            length = dataarr1.length
        }
        for (let i = 0; i < length; i++) {
            dataarr2.push(dataarr1[i])
        }
        // console.log(dataarr1.length,length)
        res.json({
            code: 200,
            msg: "获取评论成功",
            data: dataarr2,
            count
        })
    } else {  // 按时间排序
        let data = await Comment.find({ isOne: true }).populate("push_user_id").sort({ push_time: -1 }).limit(pageSize * num)

        let count = await Comment.find({}).countDocuments()

        let dataarr1 = JSON.parse(JSON.stringify(data))
        // 上面获取到的都是一级评论
        // 遍历一级评论，获取各个评论下的回复评论，按时间降序排列
        for (let i = 0; i < dataarr1.length; i++) {
            let data1 = await Comment.find({ zhu_id: data[i]._id }).populate("push_user_id").populate("push_usered_id").sort({ push_time: -1 })
            dataarr1[i].er_arr = data1 || []
        }

        res.json({
            code: 200,
            msg: "获取评论成功",
            data: dataarr1,
            count
        })
    }

})

module.exports = work